<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="任务" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入任务"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskstatus">
        <el-select v-model="queryParams.taskstatus" clearable filterable placeholder="请选择任务状态" size="small">
          <el-option
            v-for="dict in taskstatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          v-hasPermi="['task:task:add']"-->
    <!--          icon="el-icon-plus"-->
    <!--          plain-->
    <!--          size="mini"-->
    <!--          type="primary"-->
    <!--          @click="handleAdd"-->
    <!--        >新增-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          v-hasPermi="['task:task:edit']"-->
    <!--          :disabled="single"-->
    <!--          icon="el-icon-edit"-->
    <!--          plain-->
    <!--          size="mini"-->
    <!--          type="success"-->
    <!--          @click="handleUpdate"-->
    <!--        >修改-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          v-hasPermi="['task:task:remove']"-->
    <!--          :disabled="multiple"-->
    <!--          icon="el-icon-delete"-->
    <!--          plain-->
    <!--          size="mini"-->
    <!--          type="danger"-->
    <!--          @click="handleDelete"-->
    <!--        >删除-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          v-hasPermi="['task:task:export']"-->
    <!--          icon="el-icon-download"-->
    <!--          plain-->
    <!--          size="mini"-->
    <!--          type="warning"-->
    <!--          @click="handleExport"-->
    <!--        >导出-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->

    <!--    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">-->
    <el-table v-loading="loading" :data="taskList">
<!--      <el-table-column align="center" type="selection" width="55"/>-->
      <el-table-column align="center" label="任务id" prop="id"/>
      <el-table-column align="center" label="任务" prop="name"/>
      <el-table-column align="center" label="任务表述" prop="des"/>
      <el-table-column :formatter="taskstatusFormat" align="center" label="任务状态" prop="taskstatus"/>
      <el-table-column align="center" label="开始时间" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="结束时间" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改任务列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addTask, delTask, exportTask, getTask, listTaskMe, updateTask} from "@/api/task/task";
import {parseTime} from "../../../utils/neu";

export default {
  name: "Task",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务列表表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务状态字典
      taskstatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        taskstatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rudesles: {
        name: [
          {required: true, message: "任务不能为空", trigger: "blur"}
        ],
        des: [
          {required: true, message: "任务表述不能为空", trigger: "blur"}
        ],
        taskstatus: [
          {required: true, message: "任务状态不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("task_status").then(response => {
      this.taskstatusOptions = response.data;
    });
  },
  methods: {
    /**
     * 计算两个日期的差值（默认返回天数）
     * @param {string|Date} date1 第一个日期
     * @param {string|Date} date2 第二个日期
     * @param {string} unit 单位：'ms'（毫秒）、's'（秒）、'm'（分）、'h'（时）、'd'（天）
     * @returns {number} 差值（取整数）
     */
    getDateDiff(date1, date2, unit = 'd') {
      // 转换为 Date 对象
      const d1 = new Date(date1);
      const d2 = new Date(date2);

      // 校验日期有效性
      if (isNaN(d1.getTime()) || isNaN(d2.getTime())) {
        throw new Error('无效的日期格式');
      }

      // console.log(d1.getTime(), d2.getTime())

      // 计算毫秒差值
      const diffMs = d1.getTime() - d2.getTime();

      // 根据单位转换
      const units = {
        ms: 1,
        s: 1000,
        m: 1000 * 60,
        h: 1000 * 60 * 60,
        d: 1000 * 60 * 60 * 24
      };

      return Math.floor(diffMs / units[unit]);
    },
    parseTime,
    /** 查询任务列表列表 */
    getList() {
      this.loading = true;
      listTaskMe(this.queryParams).then(response => {
        response.rows.forEach(item => {
          if (item.createTime > item.endTime) {
            item.taskstatus = "0"
            return
          }
          const dateDiff = this.getDateDiff(item.endTime, new Date(), 's');
          if (dateDiff > 0) {
            item.taskstatus = "1"
          } else {
            item.taskstatus = "2"
          }
        });
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    }
    ,
// 任务状态字典翻译
    taskstatusFormat(row, column) {
      return this.selectDictLabel(this.taskstatusOptions, row.taskstatus);
    }
    ,
// 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    }
    ,
// 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        des: null,
        taskstatus: "0",
        createTime: null,
        endTime: null,
        deptId: null,
      };
      this.resetForm("form");
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }
    ,
// 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务列表";
    }
    ,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务列表";
      });
    }
    ,
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除任务列表编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有任务列表数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportTask(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
}
;
</script>
